package gwtool.gui.konfliktmanager;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.concurrent.Semaphore;

import javax.swing.JDialog;
import javax.swing.WindowConstants;

import gwtool.container.DataSet;
import gwtool.gui.dataSetView.DataSetViewController;

public class KonfliktController implements ActionListener {

	private Semaphore sema = new Semaphore(0);

	private DataSet mergedSet = null;

	private KonfliktmanagerView view;

	private DataSetViewController localController;

	private DataSetViewController onlineController;

	private DataSet onlineItem;

	private JDialog dialog;

	public KonfliktController(DataSet localItem, DataSet onlineItem) {

		this.onlineItem = onlineItem;
		view = new KonfliktmanagerView(this);
		localController = new DataSetViewController(localItem, localItem.getVersion(), false);
		onlineController = new DataSetViewController(onlineItem, onlineItem.getVersion(), false);
		view.getOnlinepanel().add(onlineController.getPanel());
		view.getLokalespanel().add(localController.getPanel());
		dialog = new JDialog();
		dialog.setTitle("Konflikmanager");
		dialog.setSize(1000, 700);
		dialog.setLocationRelativeTo(null);
		dialog.add(view);
		dialog.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
		dialog.setVisible(true);
	}

	public DataSet getMergedSet() {

		try {
			sema.acquire();
		} catch (InterruptedException e) {
		}
		return mergedSet;
	}

	@Override
	public void actionPerformed(ActionEvent e) {

		if (e.getSource() == view.getBtnKonfliktlocalloesen()) {
			onlineItem.addNewDataSetItem(localController.getView().getDataFromGui());
			mergedSet = onlineItem;
			sema.release();
			dialog.dispose();
		}
		if (e.getSource() == view.getBtnKonfliktonlineloesen()) {
			onlineItem.addNewDataSetItem(localController.getView().getDataFromGui());
			mergedSet = onlineItem;
			sema.release();
			dialog.dispose();
		}
	}
}
